import React, {useCallback, useEffect, useMemo, useState} from 'react';
import {Button, Checkbox, Descriptions, Input, List, Modal, Popconfirm, Skeleton, Tooltip, Upload} from 'antd';
import {IHistoryData, states} from '../index';
import {CloudUploadOutlined, DeleteOutlined, InfoCircleOutlined} from '@ant-design/icons';
import API from '../../../utils/api';
import {UploadChangeParam, UploadFile} from 'antd/es/upload/interface';
import request from '../../../utils/request';
import {get} from 'lodash'
import './Item.less';
import {downloadFile} from "@/utils/utils";
import ex from "umi/dist";

const {Item} = Descriptions;

export type IItemProps = {
    loading: boolean;
    freshData: () => void;
    checkedList: string[];
    onCheck: (id: string, checked: boolean) => void
    onConfirmCheck: (id: string, checked: boolean) => void
    confirmIdList: string[]
} & IHistoryData;

const HistoryItem: React.FC<IItemProps> = (props) => {
    const {loading, freshData} = props;
    const [fileList, setFileList] = useState<UploadFile[]>([]);

    const [visible, setVisible] = useState(false);
    const [modalLoading, setModalLoading] = useState(false);

    const [zl, setZl] = useState<{ [key: string]: string }>({})

    const [data, setData] = useState<any>({});

    const [index, setIndex] = useState(0);

    const getFileList = (fid: string) => {
        request(API.HISTORY_FILES, {params: {id: fid}}).then(res => {
            const {data} = res;
            setFileList(data.map((d: any) => ({
                uid: d.id,
                fileId: d.id,
                name: d.fileName,
                fileName: d.fileName,
                size: 0,
                type: '',
            })))
        })
    };

    useEffect(() => {
        const id = get(data, `extendData[${index}].id`);
        if (visible && id) {
            getFileList(id)
        }
        return () => {
            if (!visible) {
                setZl({});
                setData({});
                setIndex(0);
                setFileList([]);
            }
        }
    }, [index, data, visible]);

    const coBorrowers = useMemo(() => {
        const {borrowers = [], diys = [], extendData = []} = data;
        const extend = extendData[index];
        const bos = borrowers.filter(b => b.extendId = extend.id);
        const dys = diys.filter(b => b.extendId = extend.id);
        const addones = [];
        dys.forEach(d => {
            if (!bos.find(b => b.certNo === d.certNo)) {
                addones.push(d)
            }
        });
        addones.push(...bos.filter((b: { type: string; }) => b.type === 'sub'));
        return addones
    }, [data, index]);
    const borrower = useMemo(() => {
        const {borrowers = [], extendData = []} = data;
        const extend = extendData[index];
        return borrowers.filter(b => b.extendId = extend.id).find((b: { type: string; }) => b.type === 'main')
    }, [data, index]);

    const handleFileChange = useCallback((uploadProps: UploadChangeParam) => {
        const {file, fileList: list} = uploadProps;
        if (file.status === 'done') {
            // @ts-ignore
            file.fileId = get(file, "response.data.id")
        }
        if (file.status === 'removed') {
            return;
        }
        list.forEach((item, inx) => {
            if (item.uid === file.uid) {
                list.splice(inx, 1, file);
            }
        });
        setFileList(list);
    }, []);

    const handleDownload = useCallback(
        (e: React.MouseEvent<HTMLElement>, file: any) => {
            const {target} = e;
            if ((target as HTMLElement).getAttribute('data-icon') === 'delete') {
                e.stopPropagation();
                const confirm = Modal.confirm({
                    title: '删除确认',
                    content: '是否执行删除操作',
                    onOk: () => {
                        request(API.HISTORY_DELETE_FILE, {
                            params: {id: file.fileId},
                            method: 'delete',
                        }).then((res) => {
                            if (res.success) {
                                getFileList(props.id)
                            }
                        });
                    },
                    onCancel: () => confirm.destroy(),
                });
                return false;
            }

            const url = `http://127.0.0.1:5000/file/download?id=${file.fileId}`;
            request(url, {method: 'get'}).then(res => {
                downloadFile(file.filename || file.name, res.data)
            });
            return false;
        },
        [],
    );

    const handleDelete = useCallback(() => {
        const confirm = Modal.confirm({
            title: '删除确认',
            content: '是否执行删除操作',
            onOk: () => {
                request(API.HISTORY_DELETE, {
                    params: {id: props.id},
                    method: 'delete',
                }).then((res) => {
                    if (res.success) {
                        if (props.freshData) {
                            props.freshData();
                        }
                    }
                });
            },
            onCancel: () => confirm.destroy(),
        });
    }, [props.id, props.freshData]);

    const showDetail = useCallback(() => {
        setVisible(true);
        setModalLoading(true);
        request(API.ROBOT_DETAIL, {params: {id: props.id}}).then(res => {
            const {data} = res;
            setData(data)
        }).finally(() => {
            setModalLoading(false)
        })
    }, [props.id]);

    const actions = useMemo(
        () => {
            if (props.state === 'waitUpload') {
                return [
                    <Tooltip key='info' title='详情'>
                        <InfoCircleOutlined onClick={showDetail} style={{fontSize: '20px'}}/>
                    </Tooltip>,
                    <Tooltip key="delete" title="删除单据">
                        <DeleteOutlined onClick={handleDelete} style={{fontSize: '20px'}}/>
                    </Tooltip>,
                ]
            }
            return [
                <Tooltip key='info' title='详情'>
                    <InfoCircleOutlined onClick={showDetail} style={{fontSize: '20px'}}/>
                </Tooltip>
            ]
        },
        [props.state]);

    // 提交单据至房管局系统
    const handleSubmit = useCallback(() => {
        request(API.BANK_COMMIT_TO_HOUSE, {data: {id: props.id, zl}, method: 'POST'}).then(res => {
            setVisible(false);
            if (freshData) {
                freshData()
            }
        });
    }, [props.id, freshData, zl]);

    const handleDeleteAllFiles = useCallback(() => {
        const {extendData = []} = data;
        request(API.HISTORY_DELETE_FILES, {
            params: {id: get(extendData, `[${index}].id`)},
            method: 'delete'
        }).then(res => {
            getFileList(props.id)
        })
    }, [data, index]);

    const title = (
        <div className="item-title">
            <span className="item-name">{props.customName}</span>
            <span className="item-time">{props.createTime}</span>
        </div>
    );

    const checked = props.state === 'approved' ? props.checkedList.includes(props.id) : props.confirmIdList.includes(props.id);


    const up = () => {
        if (index > 0) {
            setIndex(index - 1)
        }
    };
    const down = () => {
        const {extendData = []} = data;
        if (index < extendData - 1) {
            setIndex(index + 1)
        }
    };

    return (
        <>
            <List.Item className="list-item" actions={actions}>
                <Skeleton loading={loading} active>
                    {props.checked &&
                    <Checkbox
                        checked={checked}
                        onChange={e => {
                            if (props.state === 'confirmed') {
                                if (props.onConfirmCheck) {
                                    props.onConfirmCheck(props.id, e.target.checked)
                                }
                                return
                            }
                            if (props.onCheck) {
                                props.onCheck(props.id, e.target.checked)
                            }
                        }}
                        style={{marginRight: '16px'}}
                    />}
                    <List.Item.Meta
                        title={title}
                        description={`${props.errorMsg || props.description} - ${props.contractNo}`}
                    />
                    {get(states, props.state)}
                </Skeleton>
            </List.Item>

            <Modal
                onCancel={() => setVisible(false)}
                okText='直接提交'
                onOk={handleSubmit}
                width={1200}
                closable={false}
                maskClosable={false}
                title='抵押填报'
                destroyOnClose
                visible={visible}
            >
                <Skeleton active loading={modalLoading}>
                    {get(data, 'extendData') && get(data, 'extendData').length > 1 && (
                        <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                            <Button onClick={up} style={{margin: '0 16px'}}>
                                {'<'}
                            </Button>
                            {index}
                            <Button onClick={down} style={{margin: '0 16px'}}>
                                {'>'}
                            </Button>
                        </div>
                    )}
                    <Descriptions className='desc' bordered column={4} style={{whiteSpace: 'nowrap'}}>
                        <Item label='抵押权人姓名'>
                            <span style={{display: 'inline-block', width: '145px'}}>
                                {get(data, `extendData[${index}].qlr`)}
                            </span>
                        </Item>
                        <Item label='证件类型'>组织机构代码</Item>
                        <Item label='证件号'>
                            {get(data, `extendData[${index}].qlrCertNo`)}
                        </Item>
                        <Item label='抵押权人电话'>{get(data, `extendData[${index}].dyqrTel`)}</Item>

                        <Item label='抵押人姓名'>{get(borrower, 'name')}</Item>
                        <Item label='证件类型'>身份证</Item>
                        <Item label='证件号'>{get(borrower, 'certNo')}</Item>
                        <Item label='抵押人电话'>{get(borrower, 'telphone')}</Item>

                        {coBorrowers && !!coBorrowers.length && coBorrowers.map(coBorrower => (
                            <>
                                <Item label='抵押人姓名'>{get(coBorrower, 'name')}</Item>
                                <Item label='证件类型'>身份证</Item>
                                <Item label='证件号'>{get(coBorrower, 'certNo')}</Item>
                                <Item label='抵押人电话'>{get(coBorrower, 'telphone')}</Item>
                            </>))}

                        <Item label='债务人姓名'>{get(borrower, 'name')}</Item>
                        <Item label='证件类型'>身份证</Item>
                        <Item label='证件号'>{get(borrower, 'certNo')}</Item>
                        <Item label='债务人电话'>{get(borrower, 'telphone')}</Item>

                        {coBorrowers && !!coBorrowers.length && coBorrowers.map(coBorrower => (
                            <>
                                <Item label='债务人姓名'>{get(coBorrower, 'name')}</Item>
                                <Item label='证件类型'>身份证</Item>
                                <Item label='证件号'>{get(coBorrower, 'certNo')}</Item>
                                <Item label='债务人电话'>{get(coBorrower, 'telphone')}</Item>
                            </>))}
                        <Item label='坐落' span={4}>
                            <Input
                                disabled={props.state !== 'waitUpload'}
                                value={
                                    get(zl,
                                        get(data, `extendData[${index}].id`),
                                        get(data, `extendData[${index}].houseLocated`)
                                    )
                                }
                                onChange={e => setZl({...zl, [get(data, `extendData[${index}].id`)]: e.target.value})}
                            />
                        </Item>
                        <Item label='抵押情况' span={4}>
                            <table>
                                <tbody>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1} rowSpan={2}>房产</th>
                                    <th className='ant-descriptions-item-label' colSpan={1} rowSpan={2}>抵押面积(㎡)</th>
                                    <td className='ant-descriptions-item-content' colSpan={1}
                                        rowSpan={2}>{get(data, `extendData[${index}].buildMarea`)}</td>
                                    <th className='ant-descriptions-item-label' colSpan={1}>评估价格(元)</th>
                                    <td className='ant-descriptions-item-content'
                                        colSpan={1}>{get(data, `extendData[${index}].totalPrice`)}</td>
                                    <th className='ant-descriptions-item-label' colSpan={1} rowSpan={4}>不动产价值(元)</th>
                                    <td className='ant-descriptions-item-content' colSpan={1}
                                        rowSpan={4}>{get(data, `extendData[${index}].totalPrice`)}</td>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1}>权利价值(元)</th>
                                    <td className='ant-descriptions-item-content'
                                        colSpan={1}>{get(data, `extendData[${index}].contractAmt`)}</td>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1} rowSpan={2}>土地</th>
                                    <th className='ant-descriptions-item-label' colSpan={1} rowSpan={2}>抵押面积(㎡)</th>
                                    <td className='ant-descriptions-item-content' colSpan={1} rowSpan={2}>0</td>
                                    <th className='ant-descriptions-item-label' colSpan={1}>评估价格(元)</th>
                                    <td className='ant-descriptions-item-content' colSpan={1}>0</td>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1}>权利价值(元)</th>
                                    <td className='ant-descriptions-item-content' colSpan={1}>0</td>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' rowSpan={2} colSpan={1}>被担保债权数额<br/>（最高债权数额）<br/>（元）
                                    </th>
                                    <td className='ant-descriptions-item-content' rowSpan={2}
                                        colSpan={2}>{get(data, `extendData[${index}].contractAmt`)}</td>
                                    <th className='ant-descriptions-item-label' rowSpan={2} colSpan={1}>债务履行期限<br/>（债权确定期间）
                                    </th>
                                    <td className='ant-descriptions-item-content' rowSpan={1}
                                        colSpan={3}>{get(data, `extendData[${index}].contractStartDate`)} 起
                                    </td>
                                </tr>
                                <tr>
                                    <td className='ant-descriptions-item-content' rowSpan={1}
                                        colSpan={3}>{get(data, `extendData[${index}].contractEndDate`)} 止
                                    </td>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1}>贷款方式</th>
                                    <td className='ant-descriptions-item-content' colSpan={2}>
                                        {get(data, `extendData[${index}].loanMethod`)}
                                    </td>
                                    <th className='ant-descriptions-item-label' colSpan={1}>在建建筑物<br/>抵押范围</th>
                                    <td className='ant-descriptions-item-content' colSpan={3}/>
                                </tr>
                                <tr>
                                    <th className='ant-descriptions-item-label' colSpan={1}>抵押方式</th>
                                    <td className='ant-descriptions-item-content' colSpan={2}>
                                        {get(data, `extendData[${index}].dyMethod`)}
                                    </td>
                                    <th className='ant-descriptions-item-label' colSpan={1}>抵押顺位</th>
                                    <td className='ant-descriptions-item-content' colSpan={3}>1</td>
                                </tr>
                                </tbody>
                            </table>
                        </Item>
                        <Item label='担保范围' span={4}>
                            {get(data, `extendData[${index}].dbfw`)}
                        </Item>
                        <Item label='证明附记' span={4}>
                            无
                        </Item>
                        <Item label='登簿备注' span={4}>
                            无
                        </Item>
                        <Item label='附件' span={4}>
                            {fileList && !!fileList.length && (
                                <Popconfirm title='删除确认'
                                            onConfirm={handleDeleteAllFiles}>
                                    <Button>全部删除</Button>
                                </Popconfirm>)}
                            <Tooltip key="upload" title="上传扫描件">
                                <Upload
                                    itemRender={(originNode, file) => (
                                        <div className="download-item" onClick={e => handleDownload(e, file)}>
                                            {originNode}
                                        </div>
                                    )}
                                    multiple
                                    disabled={props.state !== 'waitUpload'}
                                    accept={'.jpg,image/jpeg,.png'}
                                    onChange={handleFileChange}
                                    fileList={fileList}
                                    action={`${API.HISTORY_UPLOAD}?id=${get(data, `extendData[${index}].id`)}`}
                                >
                                    {fileList.length ? null : <CloudUploadOutlined style={{fontSize: '20px'}}/>}
                                </Upload>
                            </Tooltip>
                        </Item>
                    </Descriptions>
                </Skeleton>
            </Modal>
        </>
    );
};

export default HistoryItem;
